import { ref } from 'vue';
export let isFetching = ref(false);
export let fetchTotal = ref(0);
export let fetchCurrent = ref(0);

// 睡眠
export function sleep(timeout) {
  return new Promise((resolve) => {
    setTimeout(resolve, timeout * 1000);
  });
}
// 获取sku列表
export function getSkuList(skus = []) {
  return new Promise(async (resolve) => {
    isFetching.value = true;
    fetchTotal.value = skus.length;
    fetchCurrent.value = 0;
    let list = [];
    try {
      for (let i = 0, len = skus.length; i < len; i++) {
        let skuId = skus[i];
        let priceList = (await getPriceList(skuId)).sort((a, b) => a - b);
        if (priceList.length) {
          list.push([skuId, priceList[0], ...priceList]);
        } else {
          list.push([skuId]);
        }
        fetchCurrent.value++;
        await sleep(0.2 * (1 + Math.random()));
      }
    } catch (err) {
    } finally {
      isFetching.value = false;
      resolve(list);
    }
  });
}
// 获取价格列表
let skuTitle = '';
export function getPriceList(skuId, pageNo = 1) {
  return new Promise(async (resolve) => {
    let priceList = [];
    try {
      let res = await fetch(
        `https://www.ozon.ru/api/entrypoint-api.bx/page/json/v2?url=${encodeURIComponent(
          `/product/${skuId}/?layout_container=pdpPage2column&layout_page_index=2`
        )}`
      );
      let data = await res.json();
      const widgetStates = data.widgetStates || {};
      let stateData = null;
      for (const key in widgetStates) {
        if (Object.prototype.hasOwnProperty.call(widgetStates, key)) {
          if (key.includes('webSellerList')) {
            stateData = JSON.parse(widgetStates[key]);
            if (stateData && stateData.sellers) {
              break;
            }
          }
        }
      }
      if (stateData && stateData.sellers) {
        priceList = stateData.sellers
          .map((item) => {
            let price = null;
            if (item.price?.cardPrice) {
              let priceItem = item.price?.cardPrice.price;
              if (priceItem) {
                price = priceItem.replace(/(&thinsp;|\s)*/gi, '').replace(/₽/gi, '');
              }
            }
            return price;
          })
          .filter((item) => !!item);
      }
    } catch (err) {
      console.info(err);
    }
    resolve(priceList);
  });
}
